package com.renwei.yunlong.activity.me;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fingdo.statelayout.StateLayout;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.YunLongApplication;
import com.renwei.yunlong.activity.news.ProblemInformationActivity;
import com.renwei.yunlong.activity.work.GuideWebActivity;
import com.renwei.yunlong.adapter.KnowSearchAdapter;
import com.renwei.yunlong.adapter.ObjectSelectAdapter;
import com.renwei.yunlong.adapter.ProblemSearchAdapter;
import com.renwei.yunlong.adapter.SpareSelectAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.KnowSearchBean;
import com.renwei.yunlong.bean.AssetSearchBean;
import com.renwei.yunlong.bean.ProblemSearchBean;
import com.renwei.yunlong.bean.ScannerObjectBean;
import com.renwei.yunlong.bean.SpareSearchBean;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.qrcode.SimpleCaptureActivity;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.view.SearchEditText;
import com.renwei.yunlong.view.SimpleOptionView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 对象查询--页面
 * <p>
 * Created by Administrator on 2017/9/6.
 */

public class MeSearchActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, TextView.OnEditorActionListener {
    private static final int REQUEST_QR_CODE = 1;
    public static final int FROM_TYPE_OBJECT = 101;
    public static final int FROM_TYPE_SPARE = 102;
    public static final int FROM_TYPE_PROBLEM = 103;
    public static final int FROM_TYPE_KNOW = 104;
    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.et_search)
    SearchEditText etSearch;
    @Bind(R.id.rl_serch_bar)
    RelativeLayout rlSerchBar;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.state_layout)
    StateLayout stateLayout;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    private int from;
    private ObjectSelectAdapter objectAdapter;
    private SpareSelectAdapter spareAdapter;
    private ProblemSearchAdapter problemAdapter;
    private KnowSearchAdapter knowAdapter;
    private int page = 1;
    private String search = ""; //搜索内容


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_search);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        from = getIntent().getIntExtra("from", 0);
        initView();
        initData();

    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                initData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                refreshLayout.setEnableLoadmore(true);
                if (from == FROM_TYPE_OBJECT) {
                    objectAdapter.clean();
                } else if (from == FROM_TYPE_SPARE) {
                    spareAdapter.clean();
                } else if (from == FROM_TYPE_PROBLEM) {
                    problemAdapter.clean();
                } else if (from == FROM_TYPE_KNOW) {
                    knowAdapter.clean();
                }
                initData();
            }
        });
        etSearch.setOnEditorActionListener(this);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(charSequence.toString())) {
                    page = 1;
                    if (from == FROM_TYPE_OBJECT) {
                        objectAdapter.clean();
                    } else if (from == FROM_TYPE_SPARE) {
                        spareAdapter.clean();
                    } else if (from == FROM_TYPE_PROBLEM) {
                        problemAdapter.clean();
                    } else if (from == FROM_TYPE_KNOW) {
                        knowAdapter.clean();
                    }
                    search = "";
                    refreshLayout.setEnableLoadmore(true);
                    initData();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        TextView titleView = simpleTileView.getTitleView();
        titleView.setOnClickListener(this);

        if (from == FROM_TYPE_OBJECT) {
            simpleTileView.setRightOption(R.mipmap.scroll, this);
            simpleTileView.setTitle("对象查询");
            Drawable titleLeft = getResources().getDrawable(R.mipmap.icon_title_help);
            titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
            titleView.setCompoundDrawables(null, null, titleLeft, null);
            titleView.setCompoundDrawablePadding(10);

            objectAdapter = new ObjectSelectAdapter(this);
            objectAdapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                @Override
                public void onItemClick(View view, int position) {
                    ObjectInformationtActivity.OpenAcitivity(mContext, "对象详情", "0",
                            objectAdapter.getItem(position).getAssetId(), objectAdapter.getItem(position).getAssetName());
                }
            });
            recyclerView.setAdapter(objectAdapter);
        } else if (from == FROM_TYPE_SPARE) {
            simpleTileView.setTitle("备件库查询");
            Drawable titleLeft = getResources().getDrawable(R.mipmap.icon_title_help);
            titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
            titleView.setCompoundDrawables(null, null, titleLeft, null);
            titleView.setCompoundDrawablePadding(10);

            spareAdapter = new SpareSelectAdapter(this);
            spareAdapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                @Override
                public void onItemClick(View view, int position) {
                    ObjectInformationtActivity.OpenAcitivity(mContext, "备件详情", "0",
                            spareAdapter.getItem(position).getAssetId(), spareAdapter.getItem(position).getAssetName());
                }
            });
            recyclerView.setAdapter(spareAdapter);
        } else if (from == FROM_TYPE_PROBLEM) {
            etSearch.setHint("请输入问题号、简要描述");
            simpleTileView.setTitle("问题库查询");
            problemAdapter = new ProblemSearchAdapter(this);
            problemAdapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                @Override
                public void onItemClick(View view, int position) {
                    ProblemSearchBean.Rows bean = problemAdapter.getItem(position);
                    ProblemInformationActivity.OpenActivity(mContext, bean.getRequestId(), bean.getQuestionId(), "0");
                }
            });
            recyclerView.setAdapter(problemAdapter);
        } else if (from == FROM_TYPE_KNOW) {
            simpleTileView.setTitle("知识库查询");
            knowAdapter = new KnowSearchAdapter(this);
            knowAdapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                @Override
                public void onItemClick(View view, final int position) {
                    // 增加访问量
                    KnowSearchBean.RowsBean item = knowAdapter.getItem(position);
                    item.setViewNum(item.getViewNum() + 1);
                    knowAdapter.notifyItemChanged(position);

                    int knowledgeId = knowAdapter.getItem(position).getKnowledgeId();
                    KnowInformationActivity.OpenActivity(mContext, knowledgeId + "");
                }
            });
            recyclerView.setAdapter(knowAdapter);
        }


    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        if (from == FROM_TYPE_OBJECT) {
            if ("1".equals(companyType)) {
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());

            } else if ("2".equals(companyType)) {
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            }
            map.put("assetName", search);
            map.put("typeStatus", "1");
            map.put("page", page + "");
            map.put("rows", "20");
            ServiceRequestManager.getManager().getObjectList(this, JsonMapUtil.mapToJson(map), this);
        } else if (from == FROM_TYPE_SPARE) {
            if ("1".equals(companyType)) {
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());

            } else if ("2".equals(companyType)) {
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            }
            map.put("assetName", search);
            map.put("typeStatus", "0");
            map.put("page", page + "");
            map.put("rows", "20");
            ServiceRequestManager.getManager().getSpareList(this, JsonMapUtil.mapToJson(map), this);
        } else if (from == FROM_TYPE_PROBLEM) {
            if ("1".equals(companyType)) {
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            } else if ("2".equals(companyType)) {
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            }
            map.put("content", search);
            map.put("page", page + "");
            map.put("rows", "20");
            ServiceRequestManager.getManager().getQuestionList(this, JsonMapUtil.mapToJson(map), this);
        } else if (from == FROM_TYPE_KNOW) {
            if ("1".equals(companyType)) {
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            } else if ("2".equals(companyType)) {
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            }
            map.put("content", search);
            map.put("reviewStatus", "0");
            map.put("page", page + "");
            map.put("rows", "20");
            ServiceRequestManager.getManager().getKnowList(this, JsonMapUtil.mapToJson(map), this);
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        switch (requestId) {
            case 1:
                AssetSearchBean assetSearchBean = new Gson().fromJson(result, AssetSearchBean.class);
                if (assetSearchBean.getMessage().getCode() == 200) {
                    if (assetSearchBean.getRows().size() < 20) {
                        refreshLayout.setEnableLoadmore(false);
                    }
                    objectAdapter.addAll(assetSearchBean.getRows());
                    if (objectAdapter.getData().size() == 0) {
                        if (page == 1) {
                            stateLayout.showEmptyView();
                        } else {
                            stateLayout.showSearchEmptView();
                        }
                    } else {
                        stateLayout.showContentView();
                    }
                } else {//无权限访问
                    showCenterInfoMsg(assetSearchBean.getMessage().getMessage());
                }
                break;
            case 2:
                SpareSearchBean spareSearchBean = new Gson().fromJson(result, SpareSearchBean.class);
                if (spareSearchBean.getMessage().getCode() == 200) {
                    if (spareSearchBean.getRows().size() < 20) {
                        refreshLayout.setEnableLoadmore(false);
                    }
                    spareAdapter.addAll(spareSearchBean.getRows());
                    if (spareAdapter.getData().size() == 0) {
                        if (page == 1) {
                            stateLayout.showEmptyView();
                        } else {
                            stateLayout.showSearchEmptView();
                        }
                    } else {
                        stateLayout.showContentView();
                    }
                } else {//无权限访问
                    showCenterInfoMsg(spareSearchBean.getMessage().getMessage());
                }
                break;
            case 3:
                ProblemSearchBean problemSearchBean = new Gson().fromJson(result, ProblemSearchBean.class);
                if (problemSearchBean.getMessage().getCode() == 200) {
                    if (problemSearchBean.getRows().size() < 20) {
                        refreshLayout.setEnableLoadmore(false);
                    }
                    problemAdapter.addAll(problemSearchBean.getRows());
                    if (problemAdapter.getData().size() == 0) {
                        if (page == 1) {
                            stateLayout.showEmptyView();
                        } else {
                            stateLayout.showSearchEmptView();
                        }
                    } else {
                        stateLayout.showContentView();
                    }
                } else {//无权限访问
                    showCenterInfoMsg(problemSearchBean.getMessage().getMessage());
                }
                break;
            case 4:
                KnowSearchBean knowSearchBean = new Gson().fromJson(result, KnowSearchBean.class);
                if (knowSearchBean.getMessage().getCode() == 200) {
                    if (knowSearchBean.getRows().size() < 20) {
                        refreshLayout.setEnableLoadmore(false);
                    }
                    knowAdapter.addAll(knowSearchBean.getRows());
                    if (knowAdapter.getData().size() == 0) {
                        if (page == 1) {
                            stateLayout.showEmptyView();
                        } else {
                            stateLayout.showSearchEmptView();
                        }
                    } else {
                        stateLayout.showContentView();
                    }
                } else {//无权限访问
                    showCenterInfoMsg(knowSearchBean.getMessage().getMessage());
                }
                break;
            case 889:
                LogUtil.e(result);
                ScannerObjectBean bean = new Gson().fromJson(result, ScannerObjectBean.class);
                if (bean != null && bean.getRows() != null) {
                    ObjectInformationtActivity.OpenAcitivity(this, "对象详情", "0", StringUtils.value(bean.getRows().getAssetId()), StringUtils.value(bean.getRows().getAssetName()));
                } else {
                    showCenterInfoMsg("未查询到相关对象");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        stateLayout.showErrorView();
        page--;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && data.getStringExtra("result") != null) {
            String temp = StringUtils.value(data.getStringExtra("result"));
            HashMap<String, String> map = new HashMap<>();
            map.put("assetSerial", temp);
            if ("1".equals(YunLongApplication.getCompanyType())) {
                map.put("ownerCode", StringUtils.value(ownerBean.getRows().getOwnerCode()));
            } else if ("2".equals(YunLongApplication.getCompanyType())) {
                map.put("serviceProviderCode", StringUtils.value(serviceLoginBean.getRows().getServiceProviderCode()));
            }
            ServiceRequestManager.getManager().scannerObject(this, JsonMapUtil.mapToJson(map), this);
        }

    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // 当按了搜索之后关闭软键盘
            ((InputMethodManager) etSearch.getContext().getSystemService(
                    Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    MeSearchActivity.this.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
            page = 1;
            if (from == FROM_TYPE_OBJECT) {
                objectAdapter.clean();
            } else if (from == FROM_TYPE_SPARE) {
                spareAdapter.clean();
            } else if (from == FROM_TYPE_PROBLEM) {
                problemAdapter.clean();
            } else if (from == FROM_TYPE_KNOW) {
                knowAdapter.clean();
            }
            search = etSearch.getText().toString();
            initData();
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_parent://扫描
                Intent i = new Intent(MeSearchActivity.this, SimpleCaptureActivity.class);
                MeSearchActivity.this.startActivityForResult(i, REQUEST_QR_CODE);
                break;
            case R.id.option_textview_title:
                if (from == FROM_TYPE_OBJECT) {
                    GuideWebActivity.openActivity(this, Api.$().GUIDE_OBJECT_URI);
                } else if (from == FROM_TYPE_SPARE) {
                    GuideWebActivity.openActivity(this, Api.$().GUIDE_SPARE_URI);
                }
                break;
            default:
                break;
        }
    }

    public static void OpenActivity(Context context, int from) {
        Intent intent = new Intent(context, MeSearchActivity.class);
        intent.putExtra("from", from);
        context.startActivity(intent);
    }

}
